from ftplib import FTP
import argparse
from loguru import logger

from apps.website.models import Rad
from op_drf.response import ErrorResponse


def ftpconnect(rad_id,host="",username="",password="",port=""):
    # 地址，用户名和密码都使用默认值参数，未传入时从数据库中获取，传入时使用原值
    website_obj = Rad.objects.filter(is_delete=False,pk = rad_id)[0]
    assert website_obj,f"参数错误"
    logger.debug("连接ftp服务器")
    if not host:
        host = website_obj.ftp_ip
    if not username:
        username = website_obj.ftp_user
    if not password:
        password = website_obj.ftp_password
    if not port:
        port = website_obj.ftp_port

    logger.info(f"host={host};username={username};password={password};port={port}")

    try:
        ftp = FTP()
        logger.debug(1)
        ftp.connect(host,port)
        logger.debug(1)
        logger.debug(username)
        logger.debug(password)
        ftp.login(username,password)
        logger.debug(1)
        return ftp
    except:
        logger.debug("连接出现异常")
        return None


# 从本地上传文件到FTP
def uploadfile(rad_id,remotepath,localpath):
    # try:
    ftp = ftpconnect(rad_id)
    bufsize = 1024
    fp = open(localpath, "rb")
    logger.debug("STOR {}".format(remotepath))
    ftp.storbinary("STOR {}".format(remotepath), fp, bufsize)
    ftp.set_debuglevel(0)
    fp.close()
    ftp.quit()
    # except:
    #     print("执行了异常处理，其实并没有传成功")
    #     return ErrorResponse(msg="FTP连接错误，该用户名已存在!")



